//------------------------------------------------------------------------------
// <copyright file="ItemsList.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using DotBeer.Business.Entities;
using DAnton.Utilities.Helpers;

namespace DotBeer.Business.Components
{
    public class ItemsList : List<string>
    {
        #region private members

        private Item itemToExclude;
        private ItemsCollection itemsCollection;

        #endregion

        #region constructors

        public ItemsList()
        {
            if (!DesignerPropertiesHelper.IsInDesignMode())
            {
                itemsCollection = ItemsCollectionComponent.Load();
                itemsCollection.Items.CollectionChanged += new NotifyCollectionChangedEventHandler(Items_CollectionChanged);
                PopulateList();
            }
        }

        #endregion

        #region public methods

        public void Refresh()
        {
            PopulateList();
        }

        public void ExcludeItemFromList(Item item)
        {
            this.itemToExclude = item;
            PopulateList();
        }

        #endregion

        #region private methods

        void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add ||
                e.Action == NotifyCollectionChangedAction.Remove)
            {
                PopulateList();
            }
        }

        private void PopulateList()
        {
            this.Clear();

            Func<Item, bool> predicate = null;

            if (this.itemToExclude != null)
                predicate = i => i.Name != this.itemToExclude.Name;
            else
                predicate = i => true;

            var items = this.itemsCollection.Items.Where(predicate).Select(i => i.Name);
            this.AddRange(items);
        }

        #endregion
    }
}
